package com.assess.controller;

import com.assess.entity.AssessIndicator;
import com.assess.entity.AssessIndicatorMatrix;
import com.assess.entity.AssessIndicatorWeight;
import com.assess.mapper.AssessIndicatorMapper;
import com.assess.service.AssessIndicatorWeightService;
import com.assess.algorithm.MedicalAHP;
import com.assess.mapper.AssessIndicatorMatrixMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deductive.common.core.domain.AjaxResult;
import com.deductive.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/assess/weight")
@Api(tags = "指标树-权重计算与结果管理")
public class AssessIndicatorWeightController {

    @Resource
    private AssessIndicatorWeightService weightService;
    @Resource
    private AssessIndicatorMapper indicatorMapper;
    @Resource
    private AssessIndicatorMatrixMapper matrixMapper;

    @PostMapping("/compute")
    @ApiOperation("根据父节点与版本，读取矩阵和子节点并计算权重，保存到权重表")
    public AjaxResult computeAndSave(@ApiParam("父指标ID") @RequestParam Long parentId,
                                     @ApiParam("矩阵版本") @RequestParam Integer version,
                                     @ApiParam("方案/项目ID(可选)") @RequestParam(required = false) Long schemeId) {
        List<AssessIndicator> children = indicatorMapper.selectList(new LambdaQueryWrapper<AssessIndicator>()
                .eq(AssessIndicator::getParentId, parentId)
                .orderByAsc(AssessIndicator::getOrderNum));
        int n = children.size();
        if (n == 0) return AjaxResult.error("该父节点无子节点");

        List<AssessIndicatorMatrix> elements = matrixMapper.selectList(new LambdaQueryWrapper<AssessIndicatorMatrix>()
                .eq(AssessIndicatorMatrix::getParentId, parentId)
                .eq(AssessIndicatorMatrix::getVersion, version)
                .eq(schemeId != null, AssessIndicatorMatrix::getSchemeId, schemeId));

        double[][] matrix = new double[n][n];
        // 默认对角线为1
        for (int i = 0; i < n; i++) matrix[i][i] = 1.0;
        for (AssessIndicatorMatrix e : elements) {
            int i = e.getIIndex();
            int j = e.getJIndex();
            double v = e.getValue();
            matrix[i][j] = v;
            if (i != j) matrix[j][i] = 1.0 / v;
        }

        MedicalAHP.Result r = MedicalAHP.compute(matrix);
        double[] w = r.getWeights();

        List<AssessIndicatorWeight> rows = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            AssessIndicatorWeight row = new AssessIndicatorWeight();
            row.setParentId(parentId);
            row.setChildId(children.get(i).getId());
            row.setVersion(version);
            row.setWeight(w[i]);
            row.setLambdaMax(r.getLambdaMax());
            row.setCi(r.getCi());
            row.setCr(r.getCr());
            rows.add(row);
        }
        // 事务+覆盖策略可在 service 层处理，这里简化为直接写入
        weightService.saveBatchWeights(rows);
        return AjaxResult.success(rows);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询权重记录")
    public AjaxResult get(@PathVariable Long id) {
        AssessIndicatorWeight row = weightService.getById(id);
        return AjaxResult.success(row);
    }

    @GetMapping("/page")
    @ApiOperation("分页查询权重记录")
    public TableDataInfo page(@RequestParam(defaultValue = "1") long pageNum,
                              @RequestParam(defaultValue = "10") long pageSize,
                              @RequestParam(required = false) Long parentId,
                              @RequestParam(required = false) Integer version,
                              @RequestParam(required = false) Long schemeId) {
       LambdaQueryWrapper<AssessIndicatorWeight> qw = new LambdaQueryWrapper<>();
        qw.eq(parentId != null, AssessIndicatorWeight::getParentId, parentId)
          .eq(version != null, AssessIndicatorWeight::getVersion, version)
          .eq(schemeId != null, AssessIndicatorWeight::getSchemeId, schemeId)
          .orderByAsc(AssessIndicatorWeight::getParentId, AssessIndicatorWeight::getVersion, AssessIndicatorWeight::getChildId);
        Page<AssessIndicatorWeight> page = weightService.page(new Page<>(pageNum, pageSize), qw);
        TableDataInfo rsp = new TableDataInfo();
        rsp.setCode(com.deductive.common.constant.HttpStatus.SUCCESS);
        rsp.setMsg("查询成功");
        rsp.setRows(page.getRecords());
        rsp.setTotal(page.getTotal());
        return rsp;
    }

    @PostMapping
    @ApiOperation("新增权重记录")
    public AjaxResult create(@RequestBody AssessIndicatorWeight entity) {
        boolean ok = weightService.save(entity);
        return ok ? AjaxResult.success() : AjaxResult.error("保存失败");
    }

    @PutMapping
    @ApiOperation("修改权重记录")
    public AjaxResult update(@RequestBody AssessIndicatorWeight entity) {
        boolean ok = weightService.updateById(entity);
        return ok ? AjaxResult.success() : AjaxResult.error("更新失败");
    }

    @DeleteMapping
    @ApiOperation("批量删除权重记录")
    public AjaxResult delete(@ApiParam("ID列表") @RequestParam List<Long> idList) {
        boolean ok = weightService.removeByIds(idList);
        return ok ? AjaxResult.success() : AjaxResult.error("删除失败");
    }
}


